package com.ikdong.toodle.dao;

import java.util.ArrayList;
import java.util.List;

import com.ikdong.toodle.model.Authentication;
import com.ikdong.toodle.util.Constant;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class AuthDAO {
	private DataBaseHelper db;
	public AuthDAO(Context context){
		db = new DataBaseHelper(context);
	}
	
	public boolean add(Authentication auth){
		long rlt = -1;
		try{
			db.openDataBase();
			db.openDataBase();
			ContentValues values = new ContentValues();
			values.put("email", auth.getEmail());
			values.put("pass", auth.getPass());
			values.put("userid", auth.getUserId());
			values.put("key", auth.getKey());
			values.put("date_time", auth.getDateTime());
			rlt = db.getWritableDatabase().insert("Authentication", null, values);
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthDAO.add() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>-1;
	}
	
	public Authentication get(String userid){
		Authentication auth = null;
		Cursor cursor = null;
		try{
			db.openDataBase();
			String where = "userid='"+userid+"'";
			cursor = db.getReadableDatabase().query(true, "Authentication", Authentication.getColumns(), where,null, null, null, null, null);
			if(cursor!=null && cursor.moveToFirst()){
				auth = new Authentication();
				auth.setEmail(cursor.getString(0));
				auth.setPass(cursor.getString(1));
				auth.setUserId(cursor.getString(2));
				auth.setKey(cursor.getString(3));
				auth.setDateTime(cursor.getLong(4));
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthDAO.get(userid) error", e);
		}finally{
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return auth;
	}
	
	public List<Authentication> get(){
		List<Authentication> auths = new ArrayList<Authentication>();
		Cursor cursor = null;
		try{
			db.openDataBase();
			cursor = db.getReadableDatabase().query(true, "Authentication", Authentication.getColumns(), null,null, null, null, null, null);
			if(cursor!=null && cursor.moveToFirst()){
				do{
					Authentication auth = new Authentication();
					auth.setEmail(cursor.getString(0));
					auth.setPass(cursor.getString(1));
					auth.setUserId(cursor.getString(2));
					auth.setKey(cursor.getString(3));
					auth.setDateTime(cursor.getLong(4));
					auths.add(auth);
				}while(cursor.moveToNext());
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthDAO.get(userid) error", e);
		}finally{
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return auths;
	}
	
	public boolean delete(){
		long rlt = 0;
		try{
			db.openDataBase();
			rlt = db.getWritableDatabase().delete("Authentication", null,null);
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthDAO.delete() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
}
